import React, { PureComponent } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';

import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Tabs,
  Table,
  Upload,
  List,
  Avatar,
  Checkbox,
  Tooltip,
} from 'antd';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DescriptionList from '@/components/DescriptionList';
import StandardTable from '@/components/StandardTable';
import MyIcon from '@/components/MyIcon';
import IconButton from '@/components/IconButton';

import styles from './FrontApp.less';
import router from 'umi/router';

const FormItem = Form.Item;
const InputGroup = Input.Group;
const Description = DescriptionList.Description;
let cardStyle = {
  bordered: false,
  headStyle: { border: 'none' },
  style: { width: '100%' },
};

@Form.create()
@connect(({ loading }) => ({
  actionLoading: loading.effects['app/createFrontApp'] || loading.effects['app/updateFrontApp'],
}))
class FrontApp extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      type: 'create',
      appList: {
        list: [],
        pagination: {},
      },
      visible: false,
      selectedRowKeys: [],
      selectedRows: [],
    };
  }

  componentDidMount() {
    this.queryFrontAppList();
  }

  columns = [
    {
      title: formatMessage({ id: 'sysSet.Common.index' }),
      render: (text, record, index) => {
        return <span>{this.calcIndex(index)}</span>;
      },
    },
    {
      title: formatMessage({ id: 'sysSet.FrontApp.FrontApp.appName' }),
      dataIndex: 'appName',
      render: (text, record, index) => {
        return (
          <span style={{ display: 'flex', alignItems: 'center' }}>
            {
              <Tooltip title={formatMessage({ id: 'sysSet.Common.hasDisabled' })}>
                <MyIcon
                  type="icon-disable"
                  style={{ fontSize: 28, visibility: record.isLocked ? 'visible' : 'hidden' }}
                />
              </Tooltip>
            }

            {record.isLocked ? (
              text
            ) : (
              <a
                onClick={() => {
                  this.goAppConfigPage(record);
                }}
              >
                {text}
              </a>
            )}
          </span>
        );
      },
    },
    {
      title: 'appId',
      dataIndex: 'appId',
    },
  ];

  calcIndex = index => {
    const { appList } = this.state;
    let currentPage = get(appList, 'pagination.currentPage') || 1;
    let pageSize = get(appList, 'pagination.pageSize') || 50;
    return (currentPage - 1) * pageSize + index + 1;
  };

  goAppConfigPage = record => {
    router.push({
      pathname: '/system/edi/frontApp/appConfig/bind',
      query: {
        appId: record.appId,
      },
    });
  };

  queryFrontAppList = async ({ pageIndex = 1, pageSize = 50, ...params } = {}) => {
    const res = await this.props.dispatch({
      type: 'app/queryFrontAppList',
      payload: {
        queryParams: {
          pageIndex: pageIndex,
          pageSize: pageSize,
          ...params,
        },
      },
    });

    if (res.errorCode === 0) {
      this.setState({
        appList: {
          list: res.data,
          pagination: res.pagination,
        },
      });
    }
  };

  createFrontApp = params => {
    return this.props.dispatch({
      type: 'app/createFrontApp',
      payload: {
        data: params,
      },
    });
  };

  updateFrontApp = params => {
    return this.props.dispatch({
      type: 'app/updateFrontApp',
      payload: {
        pathParams: {
          id: this.state.selectedRowKeys[0],
        },
        data: params,
      },
    });
  };

  lockFrontApp = () => {
    return this.props.dispatch({
      type: 'app/lockFrontApp',
      payload: {
        data: this.state.selectedRowKeys,
      },
    });
  };

  unlockFrontApp = () => {
    return this.props.dispatch({
      type: 'app/unlockFrontApp',
      payload: {
        data: this.state.selectedRowKeys,
      },
    });
  };

  deleteFrontApp = () => {
    return this.props.dispatch({
      type: 'app/batchDeleteFrontApp',
      payload: {
        data: this.state.selectedRowKeys,
      },
    });
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      pageIndex: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.queryFrontAppList(params);
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
  };

  handleCreateClick = async () => {
    this.props.form.resetFields();
    this.setState({
      type: 'create',
      visible: true,
    });
  };

  handleEditClick = async () => {
    if (this.state.selectedRowKeys.length !== 1) {
      return;
    }
    const {
      form: { setFieldsValue, resetFields },
    } = this.props;
    this.setState({
      type: 'edit',
      visible: true,
    });
    setFieldsValue({
      appName: this.state.selectedRows[0].appName,
    });
  };

  handleLockClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }
    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.forbiden' }),
      content: formatMessage({ id: 'sysSet.FrontApp.FrontApp.sureToDisable' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.lockFrontApp();
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryFrontAppList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleUnlockClick = async () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }
    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.enable' }),
      content: formatMessage({ id: 'sysSet.FrontApp.FrontApp.sureToEnable' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.unlockFrontApp();
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryFrontAppList();
          message.success(formatMessage({ id: 'sysSet.Common.actionSuccess' }));
        }
      },
    });
  };

  handleDeleteClick = () => {
    if (!this.state.selectedRowKeys || this.state.selectedRowKeys.length === 0) {
      return;
    }
    Modal.confirm({
      title: formatMessage({ id: 'sysSet.Common.delete' }),
      content: formatMessage({ id: 'sysSet.FrontApp.FrontApp.sureToDelete' }),
      confirmLoading: true,
      onOk: async () => {
        const res = await this.deleteFrontApp();
        if (res.errorCode === 0) {
          this.setState({
            selectedRows: [],
            selectedRowKeys: [],
          });
          this.queryFrontAppList();
          message.success(formatMessage({ id: 'sysSet.Common.deleteSuccess' }));
        }
      },
    });
  };

  handleModalOnOk = () => {
    const { form } = this.props;
    form.validateFields(async (err, values) => {
      if (err) {
        return;
      }
      const res = await (this.state.type === 'create'
        ? this.createFrontApp(values)
        : this.updateFrontApp(values));
      if (res.errorCode === 0) {
        this.setState({
          selectedRows: [],
          selectedRowKeys: [],
        });
        message.success(
          `${
            this.state.type === 'create'
              ? formatMessage({ id: 'sysSet.Common.create' })
              : formatMessage({ id: 'sysSet.Common.edit' })
          }${formatMessage({ id: 'sysSet.Common.success' })}`
        );
        this.queryFrontAppList();
        this.setState({
          visible: false,
        });
      }
    });
  };

  handleModalOnCancle = () => {
    this.setState({
      visible: false,
    });
  };

  renderModal = () => {
    const { visible, type } = this.state;
    const {
      actionLoading,
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Modal
        confirmLoading={actionLoading}
        maskClosable={false}
        keyboard={false}
        title={
          type === 'create'
            ? formatMessage({ id: 'sysSet.Common.add' })
            : formatMessage({ id: 'sysSet.Common.modify' })
        }
        visible={visible}
        onOk={this.handleModalOnOk}
        onCancel={this.handleModalOnCancle}
      >
        <Form layout="horizontal" className={styles.frontApp}>
          <FormItem label={formatMessage({ id: 'sysSet.FrontApp.FrontApp.appName' })}>
            {getFieldDecorator('appName', {
              normalize: value => {
                return value && value.replace(/\s/g, '');
              },
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'sysSet.FrontApp.FrontApp.inputAppName' }),
                },
                {
                  pattern: /^[\s\S]{0,16}$/,
                  message: formatMessage({ id: 'common.limitLengthTip' }, { limit: 16 }),
                },
              ],
            })(
              <Input
                // maxLength={16}
                placeholder={formatMessage({ id: 'sysSet.FrontApp.FrontApp.inputAppName' })}
              />
            )}
          </FormItem>
        </Form>
      </Modal>
    );
  };

  renderTable = () => {
    const { loading } = this.props;
    const { selectedRowKeys, appList } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <StandardTable
        showCheckbox
        selectedRows={selectedRowKeys}
        rowSelection={rowSelection}
        rowKey="id"
        loading={loading}
        data={appList}
        columns={this.columns}
        onChange={this.handleStandardTableChange}
      />
    );
  };

  render() {
    return (
      <PageHeaderWrapper title={formatMessage({ id: 'sysSet.FrontApp.FrontApp.manageApp' })}>
        <Card {...cardStyle} className={styles.cargoApply}>
          <div style={{ marginBottom: 20, height: '30px' }}>
            {
              <div>
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.add' })}
                  icon="icon-add"
                  onClick={this.handleCreateClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.modify' })}
                  icon="icon-edit"
                  onClick={this.handleEditClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.enable' })}
                  icon="icon-enable"
                  onClick={this.handleUnlockClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.forbiden' })}
                  icon="icon-disable"
                  onClick={this.handleLockClick}
                  style={{ marginRight: '12px' }}
                />
                <IconButton
                  title={formatMessage({ id: 'sysSet.Common.delete' })}
                  icon="icon-delete"
                  onClick={this.handleDeleteClick}
                />
              </div>
            }
          </div>
          {this.renderTable()}
        </Card>
        {this.renderModal()}
      </PageHeaderWrapper>
    );
  }
}

export default FrontApp;
